﻿// Decompiled with JetBrains decompiler
// Type: TaleWorlds.CampaignSystem.Issues.LordsNeedsTutorIssueBehavior
// Assembly: TaleWorlds.CampaignSystem, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: E85F8C15-4DF6-4E9C-A58A-29177E40D07A
// Assembly location: D:\steam\steamapps\common\Mount & Blade II Bannerlord\bin\Win64_Shipping_Client\TaleWorlds.CampaignSystem.dll

using Helpers;
using System;
using System.Collections.Generic;
using System.Linq;
using TaleWorlds.CampaignSystem.Actions;
using TaleWorlds.CampaignSystem.AgentOrigins;
using TaleWorlds.CampaignSystem.Conversation;
using TaleWorlds.CampaignSystem.Encounters;
using TaleWorlds.CampaignSystem.Extensions;
using TaleWorlds.CampaignSystem.GameState;
using TaleWorlds.CampaignSystem.MapEvents;
using TaleWorlds.CampaignSystem.Party;
using TaleWorlds.CampaignSystem.Roster;
using TaleWorlds.CampaignSystem.Settlements;
using TaleWorlds.CampaignSystem.Settlements.Locations;
using TaleWorlds.Core;
using TaleWorlds.Library;
using TaleWorlds.Localization;
using TaleWorlds.ObjectSystem;
using TaleWorlds.SaveSystem;

#nullable disable
namespace TaleWorlds.CampaignSystem.Issues
{
  public class LordsNeedsTutorIssueBehavior : CampaignBehaviorBase
  {
    private const int YoungHeroAgeMinValue = 18;
    private const int YoungHeroAgeMaxValue = 23;
    private const IssueBase.IssueFrequency LordsNeedsTutorIssueFrequency = IssueBase.IssueFrequency.Common;
    private const int QuestDurationInDays = 200;
    private static List<Hero> _alreadyChosenHeroes = new List<Hero>();

    public override void RegisterEvents()
    {
      CampaignEvents.OnCheckForIssueEvent.AddNonSerializedListener((object) this, new Action<Hero>(this.OnCheckForIssue));
    }

    public void OnCheckForIssue(Hero hero)
    {
      Hero youngHero;
      if (this.ConditionsHold(hero, out youngHero))
        Campaign.Current.IssueManager.AddPotentialIssueData(hero, new PotentialIssueData(new PotentialIssueData.StartIssueDelegate(this.OnStartIssue), typeof (LordsNeedsTutorIssueBehavior.LordsNeedsTutorIssue), IssueBase.IssueFrequency.Common, (object) youngHero));
      else
        Campaign.Current.IssueManager.AddPotentialIssueData(hero, new PotentialIssueData(typeof (LordsNeedsTutorIssueBehavior.LordsNeedsTutorIssue), IssueBase.IssueFrequency.Common));
    }

    private bool SuitableCondition(Hero hero)
    {
      return (double) hero.Age >= 18.0 && (double) hero.Age < 23.0 && hero.PartyBelongedTo == null && hero.PartyBelongedToAsPrisoner == null && hero.IsActive && hero.CurrentSettlement != null && hero.Level <= 15 && !hero.IsFemale && hero.Clan != Clan.PlayerClan && !LordsNeedsTutorIssueBehavior._alreadyChosenHeroes.Contains(hero);
    }

    private bool ConditionsHold(Hero issueGiver, out Hero youngHero)
    {
      youngHero = (Hero) null;
      if (issueGiver.IsLord && issueGiver.Clan != Clan.PlayerClan && (double) issueGiver.Age > 30.0 && !issueGiver.IsMinorFactionHero)
      {
        youngHero = issueGiver.Clan.Lords.FirstOrDefault<Hero>(new Func<Hero, bool>(this.SuitableCondition));
        if (youngHero != null && youngHero != issueGiver && !this.SuitableCondition(issueGiver))
          return true;
      }
      return false;
    }

    private IssueBase OnStartIssue(in PotentialIssueData pid, Hero issueOwner)
    {
      return (IssueBase) new LordsNeedsTutorIssueBehavior.LordsNeedsTutorIssue(issueOwner, pid.RelatedObject as Hero);
    }

    public override void SyncData(IDataStore dataStore)
    {
      dataStore.SyncData<List<Hero>>("_alreadyChosenHeroes", ref LordsNeedsTutorIssueBehavior._alreadyChosenHeroes);
    }

    private static void SetAlreadyChosenHero(Hero hero)
    {
      if (LordsNeedsTutorIssueBehavior._alreadyChosenHeroes == null)
      {
        LordsNeedsTutorIssueBehavior._alreadyChosenHeroes = new List<Hero>()
        {
          hero
        };
      }
      else
      {
        if (LordsNeedsTutorIssueBehavior._alreadyChosenHeroes.Contains(hero))
          return;
        LordsNeedsTutorIssueBehavior._alreadyChosenHeroes.Add(hero);
      }
    }

    public class LordsNeedsTutorIssue : IssueBase
    {
      [SaveableField(1)]
      private Hero _youngHero;
      private const int MinimumRelationToTakeQuest = -10;

      internal static void AutoGeneratedStaticCollectObjectsLordsNeedsTutorIssue(
        object o,
        List<object> collectedObjects)
      {
        ((MBObjectBase) o).AutoGeneratedInstanceCollectObjects(collectedObjects);
      }

      protected override void AutoGeneratedInstanceCollectObjects(List<object> collectedObjects)
      {
        base.AutoGeneratedInstanceCollectObjects(collectedObjects);
        collectedObjects.Add((object) this._youngHero);
      }

      internal static object AutoGeneratedGetMemberValue_youngHero(object o)
      {
        return (object) ((LordsNeedsTutorIssueBehavior.LordsNeedsTutorIssue) o)._youngHero;
      }

      public override bool IsThereAlternativeSolution => false;

      public override bool IsThereLordSolution => false;

      public override TextObject IssueBriefByIssueGiver
      {
        get
        {
          TextObject briefByIssueGiver = new TextObject("{=VtSg9OYK}I've heard good things about you. They say that you are an accomplished warrior. [if:convo_thinking][ib:closed]Some also say an accomplished commander. I have a proposal for you. There is a young lord from my clan. He is an aspiring warrior and I must say he quite admires you. He wants to learn from you. What do you say? Are you willing to take him under your wings for a while? Let's say {QUEST_DURATION} days?");
          briefByIssueGiver.SetTextVariable("QUEST_DURATION", 200);
          return briefByIssueGiver;
        }
      }

      public override TextObject IssueAcceptByPlayer
      {
        get => new TextObject("{=a1n2zCaD}What exactly do you wish from me?");
      }

      public override TextObject IssueQuestSolutionExplanationByIssueGiver
      {
        get
        {
          return new TextObject("{=JlFfuFEC}How about you take him with you? [if:convo_merry][ib:confident3]Feed and protect him, sure, but don't treat him any differently from your companions. Let him stay with you for a year, and then let him return to us? I will send you a worthwhile gift and, perhaps more valuably, you will gain my lifelong friendship, assuming everything goes well?");
        }
      }

      public override TextObject IssueQuestSolutionAcceptByPlayer
      {
        get => new TextObject("{=iTYoUNdC}All right. I'll take him with me.");
      }

      public override TextObject Title
      {
        get
        {
          TextObject parent = new TextObject("{=XmGjTZz0}{?QUEST_GIVER.GENDER}Lady{?}Lord{\\?} Needs A Tutor");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.IssueOwner.CharacterObject, parent);
          return parent;
        }
      }

      public override TextObject Description
      {
        get
        {
          TextObject parent = new TextObject("{=MSr3HRa1}{QUEST_GIVER.NAME}, a {?QUEST_GIVER.GENDER}lady{?}lord{\\?} of the {CLAN}, wants young member of the clan trained in the arts of war.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.IssueOwner.CharacterObject, parent);
          parent.SetTextVariable("CLAN", this.IssueOwner.Clan.Name);
          return parent;
        }
      }

      public LordsNeedsTutorIssue(Hero issueOwner, Hero youngHero)
        : base(issueOwner, CampaignTime.DaysFromNow(200f))
      {
        this._youngHero = youngHero;
      }

      protected override float GetIssueEffectAmountInternal(IssueEffect issueEffect)
      {
        return issueEffect == DefaultIssueEffects.ClanInfluence ? -0.1f : 0.0f;
      }

      protected override void OnGameLoad()
      {
      }

      protected override void HourlyTick()
      {
      }

      protected override QuestBase GenerateIssueQuest(string questId)
      {
        return (QuestBase) new LordsNeedsTutorIssueBehavior.LordsNeedsTutorIssueQuest(questId, this.IssueOwner, this._youngHero);
      }

      public override IssueBase.IssueFrequency GetFrequency() => IssueBase.IssueFrequency.Common;

      protected override bool CanPlayerTakeQuestConditions(
        Hero issueGiver,
        out IssueBase.PreconditionFlags flag,
        out Hero relationHero,
        out SkillObject skill)
      {
        relationHero = (Hero) null;
        skill = (SkillObject) null;
        flag = IssueBase.PreconditionFlags.None;
        if ((double) issueGiver.GetRelationWithPlayer() < -10.0)
        {
          flag |= IssueBase.PreconditionFlags.Relation;
          relationHero = issueGiver;
        }
        if (Hero.MainHero.IsKingdomLeader)
          flag |= IssueBase.PreconditionFlags.MainHeroIsKingdomLeader;
        if (issueGiver.MapFaction.IsAtWarWith(Hero.MainHero.MapFaction))
          flag |= IssueBase.PreconditionFlags.AtWar;
        if (Clan.PlayerClan.Tier < 2)
          flag |= IssueBase.PreconditionFlags.ClanTier;
        return flag == IssueBase.PreconditionFlags.None;
      }

      public override bool IssueStayAliveConditions()
      {
        if ((double) this._youngHero.Age < 18.0 || (double) this._youngHero.Age >= 21.0 || this._youngHero.PartyBelongedTo != null || this._youngHero.PartyBelongedToAsPrisoner != null || !this._youngHero.IsActive || this._youngHero.CurrentSettlement == null || this._youngHero.Level > 20 || this.IssueOwner.Clan == Clan.PlayerClan || this._youngHero.Clan == Clan.PlayerClan)
          return false;
        return this._youngHero.Spouse == null || this._youngHero.Children.IsEmpty<Hero>();
      }

      protected override void CompleteIssueWithTimedOutConsequences()
      {
      }
    }

    public class LordsNeedsTutorIssueQuest : QuestBase
    {
      private const int MinimumSkillGainToComment = 15;
      private const int TargetSkillPointDelta = 30;
      [SaveableField(10)]
      private Hero _youngHero;
      [SaveableField(20)]
      private bool _checkForMissionEnd;
      [SaveableField(30)]
      private bool _firstConversationInitialized;
      [SaveableField(40)]
      private bool _questCompletedStartConversation;
      [SaveableField(50)]
      private int _youngHeroBeginningSkillPoints;
      [SaveableField(60)]
      private int _randomForQuestReward;
      private int _targetSkillGain;
      [SaveableField(70)]
      private Dictionary<SkillObject, int> _oldSkillValues;
      private bool _doNotForceYoungHeroOutFromClan;
      private bool _showQuestFailedConversation;
      [SaveableField(80)]
      private JournalLog _startQuestLog;

      internal static void AutoGeneratedStaticCollectObjectsLordsNeedsTutorIssueQuest(
        object o,
        List<object> collectedObjects)
      {
        ((MBObjectBase) o).AutoGeneratedInstanceCollectObjects(collectedObjects);
      }

      protected override void AutoGeneratedInstanceCollectObjects(List<object> collectedObjects)
      {
        base.AutoGeneratedInstanceCollectObjects(collectedObjects);
        collectedObjects.Add((object) this._youngHero);
        collectedObjects.Add((object) this._oldSkillValues);
        collectedObjects.Add((object) this._startQuestLog);
      }

      internal static object AutoGeneratedGetMemberValue_youngHero(object o)
      {
        return (object) ((LordsNeedsTutorIssueBehavior.LordsNeedsTutorIssueQuest) o)._youngHero;
      }

      internal static object AutoGeneratedGetMemberValue_checkForMissionEnd(object o)
      {
        return (object) ((LordsNeedsTutorIssueBehavior.LordsNeedsTutorIssueQuest) o)._checkForMissionEnd;
      }

      internal static object AutoGeneratedGetMemberValue_firstConversationInitialized(object o)
      {
        return (object) ((LordsNeedsTutorIssueBehavior.LordsNeedsTutorIssueQuest) o)._firstConversationInitialized;
      }

      internal static object AutoGeneratedGetMemberValue_questCompletedStartConversation(object o)
      {
        return (object) ((LordsNeedsTutorIssueBehavior.LordsNeedsTutorIssueQuest) o)._questCompletedStartConversation;
      }

      internal static object AutoGeneratedGetMemberValue_youngHeroBeginningSkillPoints(object o)
      {
        return (object) ((LordsNeedsTutorIssueBehavior.LordsNeedsTutorIssueQuest) o)._youngHeroBeginningSkillPoints;
      }

      internal static object AutoGeneratedGetMemberValue_randomForQuestReward(object o)
      {
        return (object) ((LordsNeedsTutorIssueBehavior.LordsNeedsTutorIssueQuest) o)._randomForQuestReward;
      }

      internal static object AutoGeneratedGetMemberValue_oldSkillValues(object o)
      {
        return (object) ((LordsNeedsTutorIssueBehavior.LordsNeedsTutorIssueQuest) o)._oldSkillValues;
      }

      internal static object AutoGeneratedGetMemberValue_startQuestLog(object o)
      {
        return (object) ((LordsNeedsTutorIssueBehavior.LordsNeedsTutorIssueQuest) o)._startQuestLog;
      }

      public override bool IsRemainingTimeHidden => false;

      public override TextObject Title
      {
        get
        {
          TextObject parent = new TextObject("{=XmGjTZz0}{?QUEST_GIVER.GENDER}Lady{?}Lord{\\?} Needs A Tutor");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          return parent;
        }
      }

      private TextObject PlayerStartsQuestLogText
      {
        get
        {
          TextObject parent = new TextObject("{=Celvao0J}{QUEST_GIVER.LINK} a {?QUEST_GIVER.GENDER}Lady{?}Lord{\\?} from {CLAN} clan has asked you to take a young clan member under your wings and train him for {DURATION} days. You have accepted to train him personally.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          parent.SetTextVariable("DURATION", 200);
          parent.SetTextVariable("CLAN", this.QuestGiver.Clan.EncyclopediaLinkWithName);
          return parent;
        }
      }

      private TextObject SuccessQuestLogText
      {
        get
        {
          TextObject parent = new TextObject("{=j0QKnNqK}The training of {YOUNG_HERO.LINK} has been completed successfully. Both He and his clan is grateful to you.");
          StringHelpers.SetCharacterProperties("YOUNG_HERO", this._youngHero.CharacterObject, parent);
          return parent;
        }
      }

      private TextObject FailTimedOutQuestLogText
      {
        get
        {
          TextObject parent = new TextObject("{=taz5cAtw}You failed to train the {YOUNG_HERO.LINK} enough as {QUEST_GIVER.LINK} expected. {?QUEST_GIVER.GENDER}She{?}He{\\?} is disappointed.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          StringHelpers.SetCharacterProperties("YOUNG_HERO", this._youngHero.CharacterObject, parent);
          return parent;
        }
      }

      private TextObject PupilHasDiedLogText
      {
        get
        {
          TextObject parent = new TextObject("{=abmSQFR5}{YOUNG_HERO.LINK} has died under your care. {QUEST_GIVER.LINK} is furious.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          StringHelpers.SetCharacterProperties("YOUNG_HERO", this._youngHero.CharacterObject, parent);
          return parent;
        }
      }

      private TextObject PupilEscapedLogText
      {
        get
        {
          TextObject parent = new TextObject("{=dL8196qY}{YOUNG_HERO.LINK} has escaped. Find him to continue your quest.");
          StringHelpers.SetCharacterProperties("YOUNG_HERO", this._youngHero.CharacterObject, parent);
          return parent;
        }
      }

      private TextObject WarDeclaredQuestCancel
      {
        get
        {
          TextObject parent = new TextObject("{=HkbK8cqw}Your clan is now at war with the {QUEST_GIVER.LINK}'s faction. Your agreement with {QUEST_GIVER.LINK} was terminated.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          return parent;
        }
      }

      private TextObject PlayerDeclaredWarQuestLogText
      {
        get
        {
          TextObject parent = new TextObject("{=bqeWVVEE}Your actions have started a war with {QUEST_GIVER.LINK}'s faction. {?QUEST_GIVER.GENDER}She{?}He{\\?} cancels your agreement and the quest is a failure.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          return parent;
        }
      }

      private TextObject PlayerKickedYoungHeroFromClan
      {
        get
        {
          TextObject parent = new TextObject("{=x3f1w3Gc}You have kicked {YOUNG_HERO.LINK} from your clan. Your agreement with {QUEST_GIVER.LINK} was terminated.");
          StringHelpers.SetCharacterProperties("YOUNG_HERO", this._youngHero.CharacterObject, parent);
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          return parent;
        }
      }

      private TextObject PlayerBecameClanLeader
      {
        get
        {
          TextObject parent = new TextObject("{=JiD05yDw}{YOUNG_HERO.LINK} now becomes the leader of his clan and your agreement with {QUEST_GIVER.LINK} was terminated.");
          StringHelpers.SetCharacterProperties("YOUNG_HERO", this._youngHero.CharacterObject, parent);
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          return parent;
        }
      }

      private TextObject PlayerMarriedYoungHero
      {
        get
        {
          TextObject parent = new TextObject("{=QGigAhFW}You have married with {YOUNG_HERO.LINK} who is the young noble you agreed to be his tutor. {QUEST_GIVER.LINK} no longer expects you to tutor {YOUNG_HERO.LINK} and wishes you a joyful marriage.");
          StringHelpers.SetCharacterProperties("YOUNG_HERO", this._youngHero.CharacterObject, parent);
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          return parent;
        }
      }

      public LordsNeedsTutorIssueQuest(string questId, Hero questGiver, Hero youngHero)
        : base(questId, questGiver, CampaignTime.DaysFromNow(200f), 0)
      {
        this._youngHero = youngHero;
        this._firstConversationInitialized = false;
        this._oldSkillValues = new Dictionary<SkillObject, int>();
        this._youngHero.SetHasMet();
        this._randomForQuestReward = MBRandom.RandomInt(2, 5);
        if (this._youngHero.GovernorOf != null)
          ChangeGovernorAction.RemoveGovernorOf(this._youngHero);
        this.SetDialogs();
        this.InitializeQuestOnCreation();
      }

      protected override void InitializeQuestOnGameLoad()
      {
        this.SetDialogs();
        this._targetSkillGain = this._youngHeroBeginningSkillPoints + 30;
      }

      protected override void SetDialogs()
      {
        Campaign.Current.ConversationManager.AddDialogFlow(this.GetYoungHeroFirstDialogFlow(), (object) this);
        Campaign.Current.ConversationManager.AddDialogFlow(this.GetYoungHeroSecondDialogFlow(), (object) this);
        Campaign.Current.ConversationManager.AddDialogFlow(this.GetYoungHeroFailedDialogFlow(), (object) this);
        this.OfferDialogFlow = DialogFlow.CreateDialogFlow("issue_classic_quest_start").NpcLine(new TextObject("{=1WxrzNXx}He'll be delighted. I'll tell him to join you as soon as possible.")).Condition(new ConversationSentence.OnConditionDelegate(this.NotableDialogCondition)).Consequence(new ConversationSentence.OnConsequenceDelegate(this.QuestAcceptedConsequences)).CloseDialog();
        this.DiscussDialogFlow = DialogFlow.CreateDialogFlow("quest_discuss").NpcLine(new TextObject("{=OoNULWKy}How is the training going? Are you happy with your student?[if:convo_delighted][ib:hip]")).Condition(new ConversationSentence.OnConditionDelegate(this.NotableDialogCondition)).Consequence((ConversationSentence.OnConsequenceDelegate) (() => Campaign.Current.ConversationManager.ConversationEndOneShot += new Action(MapEventHelper.OnConversationEnd))).BeginPlayerOptions().PlayerOption(new TextObject("{=jyxo4YgW}Yes, he is a promising boy.")).NpcLine(new TextObject("{=QsL6qcDb}That's very good to hear! Thank you.[if:convo_merry]")).CloseDialog().PlayerOption(new TextObject("{=SbbAhpTu}He is yet to prove himself actually.")).NpcLine(new TextObject("{=aHid0t6n}Give him some chance I'm sure he will prove himself soon.")).CloseDialog().EndPlayerOptions().CloseDialog();
      }

      private bool NotableDialogCondition()
      {
        StringHelpers.SetCharacterProperties("YOUNG_HERO", this._youngHero.CharacterObject);
        return Hero.OneToOneConversationHero == this.QuestGiver;
      }

      private void QuestAcceptedConsequences()
      {
        this.StartQuest();
        AddCompanionAction.Apply(Clan.PlayerClan, this._youngHero);
        MobileParty.MainParty.MemberRoster.AddToCounts(this._youngHero.CharacterObject, 1);
        this._youngHeroBeginningSkillPoints = this._youngHero.HeroDeveloper.GetTotalSkillPoints();
        this._targetSkillGain = this._youngHeroBeginningSkillPoints + 30;
        TextObject textObject = new TextObject("{=8GbGTDtL}{YOUNG_HERO.LINK}'s experience progress");
        StringHelpers.SetCharacterProperties("YOUNG_HERO", this._youngHero.CharacterObject, textObject);
        this._startQuestLog = this.AddDiscreteLog(this.PlayerStartsQuestLogText, textObject, this._youngHero.HeroDeveloper.GetTotalSkillPoints() - this._youngHeroBeginningSkillPoints, 30);
        this._checkForMissionEnd = true;
        foreach (SkillObject skillObject in (List<SkillObject>) Skills.All)
        {
          this._oldSkillValues.Add(skillObject, this._youngHero.GetSkillValue(skillObject));
          this._youngHero.HeroDeveloper.AddFocus(skillObject, 1, false);
        }
        LordsNeedsTutorIssueBehavior.SetAlreadyChosenHero(this._youngHero);
      }

      protected override void RegisterEvents()
      {
        CampaignEvents.HeroKilledEvent.AddNonSerializedListener((object) this, new Action<Hero, Hero, KillCharacterAction.KillCharacterActionDetail, bool>(this.OnHeroKilled));
        CampaignEvents.HeroPrisonerTaken.AddNonSerializedListener((object) this, new Action<PartyBase, Hero>(this.OnPrisonerTaken));
        CampaignEvents.HeroGainedSkill.AddNonSerializedListener((object) this, new Action<Hero, SkillObject, int, bool>(this.OnHeroGainedSkill));
        CampaignEvents.WarDeclared.AddNonSerializedListener((object) this, new Action<IFaction, IFaction, DeclareWarAction.DeclareWarDetail>(this.OnWarDeclared));
        CampaignEvents.OnClanLeaderChangedEvent.AddNonSerializedListener((object) this, new Action<Hero, Hero>(this.OnClanLeaderChanged));
        CampaignEvents.OnClanChangedKingdomEvent.AddNonSerializedListener((object) this, new Action<Clan, Kingdom, Kingdom, ChangeKingdomAction.ChangeKingdomActionDetail, bool>(this.OnClanChangedKingdom));
        CampaignEvents.CompanionRemoved.AddNonSerializedListener((object) this, new Action<Hero, RemoveCompanionAction.RemoveCompanionDetail>(this.OnCompanionRemoved));
        CampaignEvents.HeroesMarried.AddNonSerializedListener((object) this, new Action<Hero, Hero, bool>(this.OnHeroesMarried));
        CampaignEvents.MapEventStarted.AddNonSerializedListener((object) this, new Action<MapEvent, PartyBase, PartyBase>(this.OnMapEventStarted));
        CampaignEvents.SettlementEntered.AddNonSerializedListener((object) this, new Action<MobileParty, Settlement, Hero>(this.OnSettlementEntered));
        CampaignEvents.OnGameLoadFinishedEvent.AddNonSerializedListener((object) this, new Action(this.OnGameLoadFinished));
      }

      private void OnGameLoadFinished()
      {
        if (Settlement.CurrentSettlement == null || !Settlement.CurrentSettlement.HeroesWithoutParty.Contains(this._youngHero))
          return;
        this.SpawnYoungHeroInLordsHall();
      }

      private void OnSettlementEntered(MobileParty party, Settlement settlement, Hero hero)
      {
        if (party == null || !party.IsMainParty || !settlement.HeroesWithoutParty.Contains(this._youngHero))
          return;
        this.SpawnYoungHeroInLordsHall();
      }

      public override void OnHeroCanBeSelectedInInventoryInfoIsRequested(Hero hero, ref bool result)
      {
        this.CommonRestrictionInfoIsRequested(hero, ref result);
      }

      public override void OnHeroCanHavePartyRoleOrBeGovernorInfoIsRequested(
        Hero hero,
        ref bool result)
      {
        this.CommonRestrictionInfoIsRequested(hero, ref result);
      }

      public override void OnHeroCanLeadPartyInfoIsRequested(Hero hero, ref bool result)
      {
        this.CommonRestrictionInfoIsRequested(hero, ref result);
      }

      public override void OnHeroCanHaveQuestOrIssueInfoIsRequested(Hero hero, ref bool result)
      {
        this.CommonRestrictionInfoIsRequested(hero, ref result);
      }

      public override void OnHeroCanMarryInfoIsRequested(Hero hero, ref bool result)
      {
        this.CommonRestrictionInfoIsRequested(hero, ref result);
      }

      private void CommonRestrictionInfoIsRequested(Hero hero, ref bool result)
      {
        if (hero != this._youngHero)
          return;
        result = false;
      }

      private void OnMapEventStarted(
        MapEvent mapEvent,
        PartyBase attackerParty,
        PartyBase defenderParty)
      {
        if (!QuestHelper.CheckMinorMajorCoercion((QuestBase) this, mapEvent, attackerParty))
          return;
        QuestHelper.ApplyGenericMinorMajorCoercionConsequences((QuestBase) this, mapEvent);
      }

      private void OnHeroesMarried(Hero hero1, Hero hero2, bool showNotification = true)
      {
        if ((hero1 != Hero.MainHero || hero2 != this._youngHero) && (hero2 != Hero.MainHero || hero1 != this._youngHero))
          return;
        this._doNotForceYoungHeroOutFromClan = true;
        this.CompleteQuestWithCancel(this.PlayerMarriedYoungHero);
      }

      private void OnClanLeaderChanged(Hero oldLeader, Hero newLeader)
      {
        if (!this.IsOngoing || newLeader != this._youngHero)
          return;
        this.AddLog(this.PlayerBecameClanLeader);
        this.CompleteQuestWithFail();
      }

      private void OnCompanionRemoved(
        Hero companion,
        RemoveCompanionAction.RemoveCompanionDetail detail)
      {
        if (!this.IsOngoing || companion != this._youngHero)
          return;
        this.AddLog(this.PlayerKickedYoungHeroFromClan);
        this.CompleteQuestWithFail();
      }

      private void OnClanChangedKingdom(
        Clan clan,
        Kingdom oldKingdom,
        Kingdom newKingdom,
        ChangeKingdomAction.ChangeKingdomActionDetail detail,
        bool showNotification = true)
      {
        if (!this.QuestGiver.MapFaction.IsAtWarWith(Hero.MainHero.MapFaction))
          return;
        this.CompleteQuestWithCancel(this.WarDeclaredQuestCancel);
      }

      private void OnWarDeclared(
        IFaction faction1,
        IFaction faction2,
        DeclareWarAction.DeclareWarDetail detail)
      {
        QuestHelper.CheckWarDeclarationAndFailOrCancelTheQuest((QuestBase) this, faction1, faction2, detail, this.PlayerDeclaredWarQuestLogText, this.WarDeclaredQuestCancel);
      }

      public void OnHeroGainedSkill(Hero hero, SkillObject skill, int change = 1, bool shouldNotify = true)
      {
        if (hero != this._youngHero)
          return;
        this._startQuestLog.UpdateCurrentProgress(MBMath.ClampInt(this._youngHero.HeroDeveloper.GetTotalSkillPoints() - this._youngHeroBeginningSkillPoints, 0, 30));
        if (this._youngHero.HeroDeveloper.GetTotalSkillPoints() < this._targetSkillGain)
          return;
        this._questCompletedStartConversation = true;
      }

      private void OnPrisonerTaken(PartyBase capturer, Hero prisoner)
      {
        if (prisoner != Hero.MainHero || !this._youngHero.IsPlayerCompanion || MobileParty.MainParty.MapEventSide == null || !MobileParty.MainParty.MapEventSide.Parties.First<MapEventParty>((Func<MapEventParty, bool>) (x => x.Party == PartyBase.MainParty)).Troops.FindIndexOfCharacter(this._youngHero.CharacterObject).IsValid)
          return;
        this.AddLog(this.PupilEscapedLogText);
        EndCaptivityAction.ApplyByEscape(this._youngHero);
      }

      private void OnHeroKilled(
        Hero victim,
        Hero killer,
        KillCharacterAction.KillCharacterActionDetail detail,
        bool showNotification = true)
      {
        if (victim != this._youngHero)
          return;
        this.AddLog(this.PupilHasDiedLogText);
        this.RelationshipChangeWithQuestGiver = -40;
        this.CompleteQuestWithFail();
      }

      protected override void HourlyTick()
      {
        if (!this.IsOngoing || Hero.MainHero.IsPrisoner || Settlement.CurrentSettlement != null || PlayerEncounter.Current != null || MapEvent.PlayerMapEvent != null || this._youngHero.PartyBelongedTo != MobileParty.MainParty || !(GameStateManager.Current.ActiveState is MapState) || (!this._checkForMissionEnd || this._firstConversationInitialized) && !this._questCompletedStartConversation)
          return;
        CampaignMapConversation.OpenConversation(new ConversationCharacterData(CharacterObject.PlayerCharacter, PartyBase.MainParty), new ConversationCharacterData(this._youngHero.CharacterObject, PartyBase.MainParty));
        if (!this._checkForMissionEnd)
          return;
        this._checkForMissionEnd = false;
      }

      private void SpawnYoungHeroInLordsHall()
      {
        Monster monsterWithSuffix = FaceGen.GetMonsterWithSuffix(this._youngHero.CharacterObject.Race, "_settlement");
        (string, Monster) valueTuple = (ActionSetCode.GenerateActionSetNameWithSuffix(monsterWithSuffix, this._youngHero.CharacterObject.IsFemale, "_lord"), monsterWithSuffix);
        IFaction mapFaction1 = this._youngHero.MapFaction;
        uint color1 = mapFaction1 != null ? mapFaction1.Color : 4291609515U;
        IFaction mapFaction2 = this._youngHero.MapFaction;
        uint color2 = mapFaction2 != null ? mapFaction2.Color : 4291609515U;
        AgentData agentData = new AgentData((IAgentOriginBase) new SimpleAgentOrigin((BasicCharacterObject) this._youngHero.CharacterObject)).Monster(valueTuple.Item2).NoHorses(true).ClothingColor1(color1).ClothingColor2(color2);
        LocationComplex.Current.GetLocationWithId("lordshall").AddCharacter(new LocationCharacter(agentData, new LocationCharacter.AddBehaviorsDelegate(SandBoxManager.Instance.AgentBehaviorManager.AddFixedCharacterBehaviors), "sp_notable", true, LocationCharacter.CharacterRelations.Neutral, valueTuple.Item1, true));
      }

      private DialogFlow GetYoungHeroFirstDialogFlow()
      {
        return DialogFlow.CreateDialogFlow("start", 125).NpcLine(new TextObject("{=XH66Leg5}Greetings, my {?PLAYER.GENDER}lady{?}lord{\\?}. I have heard much of your deeds. Thank you for agreeing to train me. I hope I won't disappoint you.[if:convo_grateful][ib:demure]")).Condition((ConversationSentence.OnConditionDelegate) (() => Hero.OneToOneConversationHero == this._youngHero && !this._firstConversationInitialized)).Consequence((ConversationSentence.OnConsequenceDelegate) (() => Campaign.Current.ConversationManager.ConversationEndOneShot += new Action(this.FirstConversationEndConsequence))).BeginPlayerOptions().PlayerOption(new TextObject("{=oJJiKTSL}You are welcome.")).NpcLine(new TextObject("{=wlKtDR2z}Thank you, {?PLAYER.GENDER}my lady{?}sir{\\?}.")).CloseDialog().PlayerOption(new TextObject("{=FHeJ8bsX}We will see about that.")).NpcLine(new TextObject("{=kc3RfwFb}I'll try to be useful to you, {?PLAYER.GENDER}my lady{?}sir{\\?}.")).EndPlayerOptions().PlayerLine(new TextObject("{=kJwpbptU}Well, try to stay close to me at all times and try to learn as much as you can.")).NpcLine(new TextObject("{=EaifHOao}Yes, {?PLAYER.GENDER}my lady{?}sir{\\?}, I will.")).CloseDialog();
      }

      private DialogFlow GetYoungHeroFailedDialogFlow()
      {
        return DialogFlow.CreateDialogFlow("start", 125).NpcLine(new TextObject("{=vbbc6sIU}I regret to tell you that my progress under your tutelage is not satisfactory. I should return to my clan to resume my studies. Thank you for your trouble anyway.")).Condition((ConversationSentence.OnConditionDelegate) (() => Hero.OneToOneConversationHero == this._youngHero && this._showQuestFailedConversation)).CloseDialog();
      }

      private void FirstConversationEndConsequence()
      {
        this._youngHero.SetHasMet();
        this._firstConversationInitialized = true;
      }

      private DialogFlow GetYoungHeroSecondDialogFlow()
      {
        return DialogFlow.CreateDialogFlow("start", 125).BeginNpcOptions().NpcOption(new TextObject("{=APEBfqyW}Greetings my {?PLAYER.GENDER}lady{?}lord{\\?}. Do you wish something from me?[if:convo_innocent_smile][ib:normal2]"), new ConversationSentence.OnConditionDelegate(this.default_conversation_with_young_hero_condition)).BeginPlayerOptions().PlayerOption(new TextObject("{=BO0f1Klt}So - how do you find life in our company? Is it all you expected?.")).NpcLine(new TextObject("{=e3e79n9B}It is all I expected and more, captain. I am glad that you took me with you.[if:convo_grateful][ib:normal2]")).PlayerLine(new TextObject("{=dbG3PGXL}I'm glad you think that way. Combat aside, have you learned anything special?")).NpcLine(new TextObject("{=8L9W34D6}{NPC_EXPERIENCE_LINE}")).Condition(new ConversationSentence.OnConditionDelegate(this.npc_experience_line_condition)).PlayerLine(new TextObject("{=Rh0DlvvE}I'm glad you see it that way. Go on. Continue your training.")).NpcLine(new TextObject("{=dnvPDnzS}I will, my {?PLAYER.GENDER}lady{?}lord{\\?}. Thank you[if:convo_grateful][ib:demure]")).CloseDialog().PlayerOption(new TextObject("{=Lk6ln3sR}We seem to have got separated but I have found you. Join me, as we need to continue your training.")).Condition(new ConversationSentence.OnConditionDelegate(this.PupilJoinMeCondition)).NpcLine(new TextObject("{=0coOJAvg}Yes, {?PLAYER.GENDER}madam{?}sir{\\?}. Thank you.")).Consequence((ConversationSentence.OnConsequenceDelegate) (() => MobileParty.MainParty.MemberRoster.AddToCounts(this._youngHero.CharacterObject, 1))).CloseDialog().EndPlayerOptions().NpcOption(new TextObject("{=kUbovNbE}My {?PLAYER.GENDER}lady{?}lord{\\?}. The agreed training time with you is over. I thank you for everything. It's been a very productive for me.[if:convo_delighted][ib:demure]"), new ConversationSentence.OnConditionDelegate(this.quest_finished_conversation_with_young_hero_condition)).PlayerLine(new TextObject("{=bS0bBgp3}I'm happy to hear this. Tell me, what is the most important lesson you've learned from me?")).NpcLine(new TextObject("{=8L9W34D6}{NPC_EXPERIENCE_LINE}")).Condition(new ConversationSentence.OnConditionDelegate(this.npc_experience_line_condition)).PlayerLine(new TextObject("{=orprhyYl}I'm glad you see it that way. Very well then, off you go. Send my regards to your family. I hope to see you again one day. I am sure you will make an excellent commander.")).NpcLine(new TextObject("{=IBXfCLMp}I certainly hope too {?PLAYER.GENDER}lady{?}lord{\\?}! Again, I want to thank you for everything, before I go, please accept this gift as a humble gratitude.[if:convo_calm_friendly]")).Consequence(new ConversationSentence.OnConsequenceDelegate(this.QuestCompletedWithSuccessAfterConversation)).CloseDialog().EndNpcOptions();
      }

      private bool PupilJoinMeCondition()
      {
        return MobileParty.MainParty.MemberRoster.GetTroopRoster().All<TroopRosterElement>((Func<TroopRosterElement, bool>) (x => x.Character != this._youngHero.CharacterObject));
      }

      private void QuestCompletedWithSuccessAfterConversation()
      {
        this.RelationshipChangeWithQuestGiver = 25;
        ChangeRelationAction.ApplyPlayerRelation(this._youngHero, 15);
        this.CompleteQuestWithSuccess();
        this.AddLog(this.SuccessQuestLogText);
        ItemObject elementWithPredicate = Items.All.GetRandomElementWithPredicate<ItemObject>((Func<ItemObject, bool>) (x => x.IsTradeGood && x.ItemCategory == DefaultItemCategories.Jewelry));
        TextObject message = new TextObject("{=lWvuM5aj}{GIFT_NUMBER} pieces of {JEWELRY} have been added to your inventory.");
        message.SetTextVariable("GIFT_NUMBER", this._randomForQuestReward);
        message.SetTextVariable("JEWELRY", elementWithPredicate.Name);
        MBInformationManager.AddQuickInformation(message);
        MobileParty.MainParty.ItemRoster.AddToCounts(elementWithPredicate, this._randomForQuestReward);
        GainRenownAction.Apply(Hero.MainHero, 5f);
      }

      private bool npc_experience_line_condition()
      {
        List<KeyValuePair<LordsNeedsTutorIssueBehavior.LordsNeedsTutorIssueQuest.ExperienceIncreaseCondition, TextObject>> keyValuePairList = new List<KeyValuePair<LordsNeedsTutorIssueBehavior.LordsNeedsTutorIssueQuest.ExperienceIncreaseCondition, TextObject>>();
        keyValuePairList.Add(new KeyValuePair<LordsNeedsTutorIssueBehavior.LordsNeedsTutorIssueQuest.ExperienceIncreaseCondition, TextObject>(new LordsNeedsTutorIssueBehavior.LordsNeedsTutorIssueQuest.ExperienceIncreaseCondition(this.strength_increased_condition), new TextObject("{=hMiJvlJ5}Yes, Since we last spoke, I've learned a lot about hand-to-hand combat, my {?PLAYER.GENDER}lady{?}lord{\\?}. Correct timing and putting your whole body behind the blow means a lot more than I initially thought.[if:convo_calm_friendly][ib:warrior]")));
        keyValuePairList.Add(new KeyValuePair<LordsNeedsTutorIssueBehavior.LordsNeedsTutorIssueQuest.ExperienceIncreaseCondition, TextObject>(new LordsNeedsTutorIssueBehavior.LordsNeedsTutorIssueQuest.ExperienceIncreaseCondition(this.perception_increased_condition), new TextObject("{=TrQzYwVD}Yes, {?PLAYER.GENDER}my lady{?}lord{\\?}. Since we last spoke I had chance to increase my understanding of ranged combat. How to breath, calculate distance, and lead the target if necessary.[if:convo_calm_friendly][ib:normal]")));
        keyValuePairList.Add(new KeyValuePair<LordsNeedsTutorIssueBehavior.LordsNeedsTutorIssueQuest.ExperienceIncreaseCondition, TextObject>(new LordsNeedsTutorIssueBehavior.LordsNeedsTutorIssueQuest.ExperienceIncreaseCondition(this.endurance_increased_condition), new TextObject("{=XF7shG4k}Since we last spoke I've been training vigorously. I feel tougher, much more energetic and alive now.[if:convo_calm_friendly][ib:warrior2]")));
        keyValuePairList.Add(new KeyValuePair<LordsNeedsTutorIssueBehavior.LordsNeedsTutorIssueQuest.ExperienceIncreaseCondition, TextObject>(new LordsNeedsTutorIssueBehavior.LordsNeedsTutorIssueQuest.ExperienceIncreaseCondition(this.cunning_increased_condition), new TextObject("{=H6l9cm7I}I've been paying attention to your subtler methods, {?PLAYER.GENDER}my lady{?}lord{\\?}, I've been observing that courage and strength in numbers is not enough to win most engagements. You have to be aware of the situation and seize the opportunities when they present themselves.[if:convo_calm_friendly][ib:hip]")));
        keyValuePairList.Add(new KeyValuePair<LordsNeedsTutorIssueBehavior.LordsNeedsTutorIssueQuest.ExperienceIncreaseCondition, TextObject>(new LordsNeedsTutorIssueBehavior.LordsNeedsTutorIssueQuest.ExperienceIncreaseCondition(this.social_increased_condition), new TextObject("{=bNAbWn4E}I've been watching how you deal with different kinds of folk: how to present yourself, how to address people from various walks of life properly, how to inspire greatness to those who trust in you.[if:convo_calm_friendly][ib:confident]")));
        keyValuePairList.Add(new KeyValuePair<LordsNeedsTutorIssueBehavior.LordsNeedsTutorIssueQuest.ExperienceIncreaseCondition, TextObject>(new LordsNeedsTutorIssueBehavior.LordsNeedsTutorIssueQuest.ExperienceIncreaseCondition(this.intelligence_increased_condition), new TextObject("{=9bd0jJD8}I've been studying a lot, {?PLAYER.GENDER}my lady{?}lord{\\?}. The manuscripts I've acquired on the way on various subjects are invaluable. Seeing professionals in action complements the theoretical knowledge I've learned from the manuscripts.[if:convo_calm_friendly][ib:demure2]")));
        MBList<TextObject> e = new MBList<TextObject>();
        foreach (KeyValuePair<LordsNeedsTutorIssueBehavior.LordsNeedsTutorIssueQuest.ExperienceIncreaseCondition, TextObject> keyValuePair in keyValuePairList)
        {
          if (keyValuePair.Key())
            e.Add(keyValuePair.Value);
        }
        if (e.Count != 0)
        {
          MBTextManager.SetTextVariable("NPC_EXPERIENCE_LINE", e.GetRandomElement<TextObject>(), false);
          return true;
        }
        MBTextManager.SetTextVariable("NPC_EXPERIENCE_LINE", new TextObject("{=XFafAocV}Nothing specific, captain. But I'm paying close attention to everything you do.[if:convo_excited][ib:nervous]"), false);
        return true;
      }

      private bool default_conversation_with_young_hero_condition()
      {
        return Hero.OneToOneConversationHero == this._youngHero && this._firstConversationInitialized && !this._questCompletedStartConversation && !this._showQuestFailedConversation;
      }

      private bool quest_finished_conversation_with_young_hero_condition()
      {
        return Hero.OneToOneConversationHero == this._youngHero && this._firstConversationInitialized && this._questCompletedStartConversation && !this._showQuestFailedConversation;
      }

      private bool strength_increased_condition()
      {
        int num = 0;
        foreach (KeyValuePair<SkillObject, int> oldSkillValue in this._oldSkillValues)
        {
          if (oldSkillValue.Key.CharacterAttribute == DefaultCharacterAttributes.Vigor)
            num += this._youngHero.GetSkillValue(oldSkillValue.Key) - oldSkillValue.Value;
        }
        return num > 15;
      }

      private bool perception_increased_condition()
      {
        int num = 0;
        foreach (KeyValuePair<SkillObject, int> oldSkillValue in this._oldSkillValues)
        {
          if (oldSkillValue.Key.CharacterAttribute == DefaultCharacterAttributes.Control)
            num += this._youngHero.GetSkillValue(oldSkillValue.Key) - oldSkillValue.Value;
        }
        return num > 15;
      }

      private bool endurance_increased_condition()
      {
        int num = 0;
        foreach (KeyValuePair<SkillObject, int> oldSkillValue in this._oldSkillValues)
        {
          if (oldSkillValue.Key.CharacterAttribute == DefaultCharacterAttributes.Endurance)
            num += this._youngHero.GetSkillValue(oldSkillValue.Key) - oldSkillValue.Value;
        }
        return num > 15;
      }

      private bool cunning_increased_condition()
      {
        int num = 0;
        foreach (KeyValuePair<SkillObject, int> oldSkillValue in this._oldSkillValues)
        {
          if (oldSkillValue.Key.CharacterAttribute == DefaultCharacterAttributes.Cunning)
            num += this._youngHero.GetSkillValue(oldSkillValue.Key) - oldSkillValue.Value;
        }
        return num > 15;
      }

      private bool social_increased_condition()
      {
        int num = 0;
        foreach (KeyValuePair<SkillObject, int> oldSkillValue in this._oldSkillValues)
        {
          if (oldSkillValue.Key.CharacterAttribute == DefaultCharacterAttributes.Social)
            num += this._youngHero.GetSkillValue(oldSkillValue.Key) - oldSkillValue.Value;
        }
        return num > 15;
      }

      private bool intelligence_increased_condition()
      {
        int num = 0;
        foreach (KeyValuePair<SkillObject, int> oldSkillValue in this._oldSkillValues)
        {
          if (oldSkillValue.Key.CharacterAttribute == DefaultCharacterAttributes.Intelligence)
            num += this._youngHero.GetSkillValue(oldSkillValue.Key) - oldSkillValue.Value;
        }
        return num > 15;
      }

      protected override void OnFinalize()
      {
        if (!this._youngHero.IsAlive)
          return;
        if (this._youngHero.CompanionOf == Clan.PlayerClan)
        {
          RemoveCompanionAction.ApplyAfterQuest(Clan.PlayerClan, this._youngHero);
          if (!this._doNotForceYoungHeroOutFromClan)
            this._youngHero.Clan = this.QuestGiver.Clan;
          foreach (Hero child in (List<Hero>) this._youngHero.Children)
            child.Clan = this._youngHero.Clan;
          if (this._youngHero.Spouse != null)
            this._youngHero.Spouse.Clan = this._youngHero.Clan;
        }
        foreach (SkillObject skill in (List<SkillObject>) Skills.All)
          this._youngHero.HeroDeveloper.AddFocus(skill, -1, false);
      }

      protected override void OnCompleteWithSuccess()
      {
      }

      protected override void OnTimedOut()
      {
        this.AddLog(this.FailTimedOutQuestLogText);
        this.RelationshipChangeWithQuestGiver = -10;
        this._showQuestFailedConversation = true;
        if (Settlement.CurrentSettlement != null || PlayerEncounter.Current != null || MapEvent.PlayerMapEvent != null || !(GameStateManager.Current.ActiveState is MapState))
          return;
        CampaignMapConversation.OpenConversation(new ConversationCharacterData(CharacterObject.PlayerCharacter, PartyBase.MainParty), new ConversationCharacterData(this._youngHero.CharacterObject, PartyBase.MainParty));
      }

      private delegate bool ExperienceIncreaseCondition();
    }

    public class LordsNeedsTutorIssueTypeDefiner : SaveableTypeDefiner
    {
      public LordsNeedsTutorIssueTypeDefiner()
        : base(80120)
      {
      }

      protected override void DefineClassTypes()
      {
        this.AddClassDefinition(typeof (LordsNeedsTutorIssueBehavior.LordsNeedsTutorIssue), 1);
        this.AddClassDefinition(typeof (LordsNeedsTutorIssueBehavior.LordsNeedsTutorIssueQuest), 2);
      }
    }
  }
}
